package com.operate.api.app.pay.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.operate.api.app.pay.domain.vo.ApplePayVO;
import com.operate.api.app.pay.service.IPayService;
import com.operate.api.base.ApiIndex;
import com.operate.api.base.R;
import com.operate.api.base.Type;
import com.operate.util.IosVerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;


@Api( tags = ApiIndex.AppPackageController)
@RequestMapping(value = "/api/pay")
@RestController
@Slf4j
public class ALiPayController {

    @Autowired
    IPayService service;
    @Autowired
    IosVerifyUtil iosVerifyUtil;



    @ApiOperation(value = "支付宝异步回调", hidden = true)
    @PostMapping(value = "/a_callback")
    public void a_callback(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        service.al_callback(request, response);

    }

    @ApiOperation(value = "微信异步回调", hidden = true)
    @PostMapping(value = "/w_callback")
    public void w_callback(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        service.wx_callback(request, response);

    }

    @ApiOperation(value = "Ios客户端内购支付")
    @PostMapping(value = "/applePay")
    @SaCheckLogin
    public R applePay(HttpServletRequest request,@RequestBody ApplePayVO applePayVo) {
        String receipt_data = applePayVo.getReceiptData();
        String transactionID = applePayVo.getTransactionID();
        String verifyResult = iosVerifyUtil.buyAppVerify(receipt_data,applePayVo.getType());
        if (verifyResult == null) {
            log.info("苹果验签失败" );
            JSONObject jsonObject= new JSONObject();
            jsonObject.put("verify_status",-1);
            return new R(Type.APPLE_PAY_NO).setData(jsonObject);
        } else {
            // 苹果验证有返回结果
            log.info("验签成功，苹果平台返回JSON:" + verifyResult);
            JSONObject job = JSONObject.parseObject(verifyResult);
            String states = job.getString("status");
            //获取苹果系统服务器验证结果数据处理自己的业务
            R appPayR = service.getAppPay(states, job, transactionID, request, applePayVo);
            return appPayR;
        }
    }

}